import { getUser } from '@/services/user';
import { history } from 'umi';

const namespace = 'global';

export default {
  namespace,
  state: {
    // 当前用户
    user: null,
  },
  effects: {
    *login({ payload }, { call, put }) {
      const res = yield call(getUser, { id: 101 });
      if (res.success) {
        const { name, id } = res.data;
        yield put({
          type: 'save',
          payload: { user: name },
        });
        window.sessionStorage.clear();
        window.sessionStorage.setItem('User', name);
        window.sessionStorage.setItem('Token', id);
      }
      return res;
    },
    *logout({}, { put }) {
      yield put({
        type: 'save',
        payload: { user: null },
      });
      window.sessionStorage.clear();
      history.replace({
        pathname: '/login',
        search: `timestamp=${new Date().getTime()}`,
      });
    },
  },
  // 同步
  reducers: {
    // 通用
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
  subscriptions: {
    // 监听路由变化，鼠标，键盘变化，服务器连接变化等
    setup({ dispatch, history }) {
      const user = window.sessionStorage.getItem('User');
      // 如果会话中用户信息已存，则存入State
      if (user) {
        dispatch({
          type: 'save',
          payload: {
            user,
          },
        });
      }
      history.listen(({ location }) => {
        console.log(location.pathname);
      });
    },
  },
};
